package com.schoolcloud.front.mq.consumer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.schoolcloud.common.model.NotificationRequest;
import com.schoolcloud.front.config.RabbitMQConfig;
import com.schoolcloud.front.config.SaTokenWebSocketHandler;
import com.schoolcloud.front.dto.WsMessageDTO;
import com.schoolcloud.front.entity.Notifications;
import com.schoolcloud.front.service.NotificationsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
@Slf4j
public class NotificationConsumer {

    private final NotificationsService notificationsService;
    private final SaTokenWebSocketHandler webSocketHandler;
    private final ObjectMapper objectMapper;

    private final RabbitTemplate rabbitTemplate;

    /**
     * 处理通知存储的消息
     *
     * @param notificationRequest 通知请求
     */
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = RabbitMQConfig.FRONT_NOTIFICATION_STORE_QUEUE, durable = "true"),
                    exchange = @Exchange(value = RabbitMQConfig.FRONT_NOTIFICATION_EXCHANGE, type = ExchangeTypes.TOPIC),
                    key = "notification.store.#"
            )
    })
    public void handleStoreNotification(NotificationRequest notificationRequest){
        log.info("接受存储通知：{}", notificationRequest);
        Notifications saveNotification = notificationsService.saveNotification(notificationRequest);
        log.info("存储成功,转改消息给推送队列");
        rabbitTemplate.convertAndSend(
                RabbitMQConfig.FRONT_NOTIFICATION_EXCHANGE,
                "notification.push",  // 推送专用路由键
                saveNotification
        );
    }

    /**
     * 处理通知推送的消息
     *
     * @param notificationRequest 通知请求
     */
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = RabbitMQConfig.FRONT_NOTIFICATION_PUSH_QUEUE, durable = "true"),
                    exchange = @Exchange(value = RabbitMQConfig.FRONT_NOTIFICATION_EXCHANGE, type = ExchangeTypes.TOPIC),
                    key = "notification.push.#"
            )
    })
    public void handlePushNotification(Notifications notificationRequest){
        try{
            log.info("接受推送通知：{}", notificationRequest);
            WsMessageDTO wsMessageDTO = new WsMessageDTO();
            wsMessageDTO.setType(notificationRequest.getType());
            wsMessageDTO.setSenderId(String.valueOf(notificationRequest.getSenderId()));
            wsMessageDTO.setReceiverId(String.valueOf(notificationRequest.getUserId()));
            wsMessageDTO.setContent(notificationRequest.getContent());
            wsMessageDTO.setTitle(notificationRequest.getTitle());
            String s = objectMapper.writeValueAsString(wsMessageDTO);
            String receiverId = String.valueOf(notificationRequest.getUserId());
            webSocketHandler.sendMessageToUser(receiverId,s);
            /*如果用户没有登录，则不进行推送*/
        }catch (Exception e){
            log.error("推送通知失败：{}", e.getMessage());
        }
    }
}
